package com.zyw.zhuangdian.service.impl;

import com.zyw.zhuangdian.constant.ServiceConstant;
import com.zyw.zhuangdian.dao.HistoryDao;
import com.zyw.zhuangdian.pojo.Resp;
import com.zyw.zhuangdian.pojo.dto.PageDto;
import com.zyw.zhuangdian.pojo.dto.HistoryDto;
import com.zyw.zhuangdian.service.HistoryService;
import com.zyw.zhuangdian.util.BeanConvertUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class HistoryServiceImpl implements HistoryService {
    private final HistoryDao HistoryDao;

    @Override
    public Resp<Void> addHistory(HistoryDto in) {
        Resp<Void> resp = new Resp<>();

        HistoryDao.addHistory(BeanConvertUtil.beanCovertMap(in));
        return resp;
    }

    @Override
    public Resp<Void> updateHistory(HistoryDto in) {
        Resp<Void> resp = new Resp<>();

        HistoryDao.updateHistory(BeanConvertUtil.beanCovertMap(in));
        return resp;
    }

    @Override
    public Resp<Void> deleteHistory(HistoryDto in) {
        Resp<Void> resp = new Resp<>();
        in.setStatus(ServiceConstant.STATUS_INVALID);
        HistoryDao.updateHistory(BeanConvertUtil.beanCovertMap(in));
        return resp;
    }

    @Override
    public Resp<List<HistoryDto>> listHistories(HistoryDto in) {
        Resp<List<HistoryDto>> resp = new Resp<>();
        if (in.getPage() != PageDto.DEFAULT_PAGE){
            if (in.getRow() == PageDto.DEFAULT_PAGE){
                in.setPage(PageDto.DEFAULT_PAGE);
            }else{
                in.setPage((in.getPage() - 1) * in.getRow());
            }
        }
        // 手动装配
        int count = HistoryDao.listHistoriesCount(BeanConvertUtil.beanCovertMap(in));
        if (count > 0){
            List<Map> articles = HistoryDao.listHistory(BeanConvertUtil.beanCovertMap(in));
            List<HistoryDto> dtoOuts = BeanConvertUtil.covertBeanList(articles,HistoryDto.class);
//
            resp.setData(dtoOuts);
        }

        resp.setTotal(count);
        if (in.getPage() != PageDto.DEFAULT_PAGE) {
            resp.setRecords((int) Math.ceil((double) count / (double) in.getRow()));
            resp.setPage(in.getPage());
            resp.setRow(in.getRow());
        }
        return resp;
    }
}
